package com.coin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coin.domain.*;
import com.coin.service.*;
import com.coin.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 李力
 * @description 针对表【sys_user(平台用户)】的数据库操作Service实现
 * @createDate 2025-05-24 17:08:03
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private SysUserRoleService userRoleService;

    /**
     * @Description: SysUserController
     * @Author: 李 力
     * @Date: 2025/5/28
     * @Param: current   size  mobile  fullname
     * @return: R
     */
    @Override
    public Page<SysUser> findByPage(Page<SysUser> page, String mobile, String fullname) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>();
        wrapper = wrapper.like(StrUtil.isNotEmpty(mobile), SysUser::getMobile, mobile)
                .like(StrUtil.isNotEmpty(fullname), SysUser::getFullname, fullname);
        Page<SysUser> sysUserPage = page(page, wrapper);
        List<SysUser> records = sysUserPage.getRecords();
        if (records != null && !records.isEmpty()) {
            //把用户的角色信息查询出来一起返回
            for (SysUser record : records) {
                LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper = queryWrapper.eq(SysUserRole::getUserId, record.getId());
                List<SysUserRole> list = userRoleService.list(queryWrapper);
                if (list != null && !list.isEmpty()) {
                    String collect = list.stream().
                            map(sysUserRole -> sysUserRole.getRoleId().toString())
                            .collect(Collectors.joining(","));
                    record.setRole_strings(collect);
                }
            }
        }
        return sysUserPage;
    }

    /**
     * @Description: 新增员工
     * @Author: 李 力
     * @Date: 2025/5/28
     * @Param: sysUser
     * @return: R
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUser(SysUser sysUser) {
        if (sysUser == null) {
            throw new RuntimeException("参数为空");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //1.先新增员工
        String password = sysUser.getPassword();
        //加密
        String encode = encoder.encode(password);
        sysUser.setPassword(encode);
        boolean save = save(sysUser);
        if (save) {
            //2.新增权限数据
            String roleStrings = sysUser.getRole_strings();
            if (StrUtil.isNotEmpty(roleStrings)) {
                List<SysUserRole> list = new ArrayList<>();
                String[] ids = roleStrings.split(",");
                for (String id : ids) {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setRoleId(Long.parseLong(id));
                    userRole.setUserId(sysUser.getId());
                    list.add(userRole);
                }
                return userRoleService.saveBatch(list);
            }
        }
        return false;
    }


    /**
     * @Description: 修改员工
     * @Author: 李 力
     * @Date: 2025/5/28
     * @Param: sysUser
     * @return: R
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(SysUser sysUser) {
        if (sysUser == null) {
            throw new RuntimeException("参数为空");
        }
        //其他校验略过
        boolean result = updateById(sysUser);
        if (result) {
            String roleStrings = sysUser.getRole_strings();
            if (StrUtil.isNotEmpty(roleStrings)) {
                String[] roleIds = roleStrings.split(",");
                LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper = queryWrapper.eq(SysUserRole::getUserId, sysUser.getId());
                boolean remove = userRoleService.remove(queryWrapper);
                if (remove) {
                    List<SysUserRole> list = new ArrayList<>();
                    for (String roleId : roleIds) {
                        SysUserRole userRole = new SysUserRole();
                        userRole.setRoleId(Long.parseLong(roleId));
                        userRole.setUserId(sysUser.getId());
                        list.add(userRole);
                    }
                    return userRoleService.saveBatch(list);
                }
            }
        }
        return false;
    }

    /**
     * @Description: 删除员工
     * @Author: 李 力
     * @Date: 2025/5/28
     * @Param: ids
     * @return: R
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new RuntimeException("参数为空");
        }
        //删除用户
        boolean result = removeBatchByIds(Arrays.asList(ids));
        if (result) {
            //删除角色
            LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper = queryWrapper.in(SysUserRole::getUserId, Arrays.asList(ids));
            return userRoleService.remove(queryWrapper);
        }
        return false;
    }

    /**
     * @Description:
     * @Author: 李 力
     * @Date: 2025/6/9
     * @Param: userId
     * @return: R
     */
    @Override
    public String getUserNameById(Long userId) {
        if (userId == null) {
            throw new RuntimeException("参数为空");
        }
        SysUser user = getById(userId);
        if (user == null) {
            throw new RuntimeException("查无此用户");
        }
        return user.getFullname();
    }
}




